package com.shj.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.shj.entity.MenuTreeNode;
import com.shj.entity.SysMenu;
import com.shj.service.MenuTreeService;
import com.shj.service.SysMenuService;
import com.shj.service.SysRoleMenuService;
import net.sf.json.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author songhuajian
 * @Description: TODO 权限树业务实现类
 * @date 2020/5/3 0:07
 **/
@Service("menuTreeService")
public class MenuTreeServiceImpl implements MenuTreeService {
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /**
     * @Description 生成权限树
     * @author songhuajian
     * @date 2020/5/3 0:36
     */
    @Override
    public MenuTreeNode tree(SysMenu sysMenu, String roleId, boolean recursive) {
        MenuTreeNode node = new MenuTreeNode(sysMenu);
        List<SysMenu> subMenuList = sysMenuService.findChildren(sysMenu.getMenuId());
        if (!subMenuList.isEmpty()) {
            // 递归查询子节点
            if (recursive) {
                List<MenuTreeNode> children = new ArrayList<MenuTreeNode>();
                for (SysMenu m : subMenuList) {
                    MenuTreeNode t = tree(m,roleId, true);
                    //如果角色包含该菜单则默认选中
                    if(roleId != null){
                        t.setChecked(sysRoleMenuService.hasRole(roleId, m.getMenuId()));
                    }
                    children.add(t);
                }
                node.setChildren(children);
            }
        }
        return node;
    }

    @Override
    public List<MenuTreeNode> getChildNodeList(List<MenuTreeNode> nodeList) {
        List<MenuTreeNode> allNodes=new ArrayList<MenuTreeNode>();
        for(MenuTreeNode node : nodeList){
            visit(node, allNodes);
        }
        return allNodes;
    }

    @Override
    public void visit(MenuTreeNode node, List<MenuTreeNode> nodes) {
        List<MenuTreeNode> children = node.getChildren();
        nodes.add(node);
        if(children != null && !children.isEmpty()){
            for(MenuTreeNode e : node.getChildren()){
                visit(e, nodes);
            }
        }
    }

    @Override
    public List<MenuTreeNode> tree(String treeId, String roleId) {
        List<MenuTreeNode> list = new ArrayList<>();
        // 构建根节点为treeId的菜单树
        List<SysMenu> sysMenuList = sysMenuService.findChildren(treeId);
        for (SysMenu sysMenu : sysMenuList) {
            list.add(tree(sysMenu, roleId, true));
        }
        return list;
    }
}
